<?php
namespace Admin\Controller;
use Admin\Logic\Controller\MainController;
use Admin\Model\RoleModel;
use Admin\Model\PermissionModel;

class RoleController extends MainController {
    /**
     * @var HospitalModel
     */

    protected $roleModel = null;
    public function _initialize(){
        $this->roleModel = new RoleModel();
         $this->permissionModel = new PermissionModel();
    }
    
    public function lists(){
        $this->assign ( 'list',  $this->roleModel->lists() );
        $this->display();
    }
    
    public function edit(){
        if(!IS_POST){
            $id = I('id');
            $this->assign ( 'info',$this->roleModel->Find($id) );
            $this->assign ( 'permissionfind',$this->roleModel->permissionFind($id) );
            //$this->assign ( 'groupinfo',  $this->permissionModel->groupinfo() );
            $this->assign ( 'permissioninfo',  $this->roleModel->permissioninfo() );
           // var_dump( $this->roleModel->permissioninfo() );
            $this->display();
        }else{
            $id = I('id');
            //var_dump($id);exit;
            if(empty($id)){               
                $data['rolename'] = I("post.rolename",'','string');
                $data['remark'] = I("post.remark",'','string');
                $map=(array)$_POST['map'];
                $data['createtime']=time();
                $res = $this->roleModel->addList($data);
                if($res){
		foreach( $map as $v )
		{
			$data_map = array();
                        $data_map['role_id']= $res;
			$data_map['permission_id']= $v;
			 M("role_permission")->add( $data_map );
		}    
                    $this->success('添加成功',U("role/lists"));
                }else{
                    $this->error('添加失败');
                }
            }else{
                $data['rolename'] = I("post.rolename",'','string');
                $data['remark'] = I("post.remark",'','string');
                $map=(array)$_POST['map'];                
                M("role")->where("id='$id'")->save( $data );
                //var_dump( M("role")->getlastsql());exit;
                //var_dump($res);exit;

                    M("role_permission")->where("role_id='$id'")->delete();
                    foreach( $map as $v )
                    {
                            $data_map = array();
                            $data_map['role_id']= $id;
                            $data_map['permission_id']= $v;
                            $res=M("role_permission")->add( $data_map );
                    }
                    $this->success("保存成功",U("role/lists"));
                
                }                
            }
        } 

    public function delete(){
        $id = I('get.id',null,'int');
        if($id){
            $res = $this->roleModel->deleteList($id);
        }
        if($res){
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }        
    


}